let fs = require('fs')

let router = require('koa-router')()

let path = require('path');



//文件进行筛选
function findFile(path) {
    let files = fs.readdirSync(path)
    return files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js'
    })
}





function rou(files, dir) {
    files.forEach(element => {
        let filePath = path.join(dir, element);
        let router_fn = require(filePath);
        for (let r in router_fn) {
            let arr = router_fn[r];
            let type = router_fn[r][0];
            if (type === 'get') {
                let fn = arr[1];
                router.get(r, fn);
            } else {
                let fn = arr[1];
                router.post(r, fn);
            }
        }
    });
}

module.exports = function (dir) {
    let temp = dir || 'controllers';
    let temps = path.resolve('.');
    let realRouter = path.join(temps, temp);
    let jsFile = findFile(realRouter);
    rou(jsFile, realRouter);
    return router.routes();
}